﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.ExtensibleStorage;
using YJKAreaCutter.Utils.XDataUtils;

namespace YJKRevitDimensionText.OneKeyPlanDim.Utility.XDataUtils
{
	public class OutWallFirstSizeDimXDataUtil
	{
		public static bool WriteXData(Element ele, string strValue)
		{
			bool result = false;
			try
			{
				OutWallFirstSizeDimXDataUtil.Instance();
				Entity entity = OutWallFirstSizeDimXDataUtil.m_xdataMgr.CreateEntity();
                OutWallFirstSizeDimXDataUtil.m_xdataMgr.SetElementEntity<string>(ele, OutWallFirstSizeDimXDataUtil.m_strFieldName, strValue, (DisplayUnitType)(-2), ref entity);
				OutWallFirstSizeDimXDataUtil.m_xdataMgr.SetElementXData(ele, entity);
				result = true;
			}
			catch
			{
			}
			return result;
		}

		public static bool ReadXData(Element ele, ref string strValue)
		{
			strValue = string.Empty;
			try
			{
                strValue = XDataManager.GetElementXData<string>(OutWallFirstSizeDimXDataUtil.m_Guid, ele, OutWallFirstSizeDimXDataUtil.m_strFieldName, (DisplayUnitType)(-2));
			}
			catch
			{
				return false;
			}
			return true;
		}

		public static bool HasExistDimesion(List<Wall> lstWall, Autodesk.Revit.DB.View view)
		{
			try
			{
				string empty = string.Empty;
				foreach (Wall wall in lstWall)
				{
					if (OutWallFirstSizeDimXDataUtil.ReadXData(wall, ref empty))
					{
						Element element = wall.Document.GetElement(empty);
						if (element != null && element.OwnerViewId.IntegerValue == view.Id.IntegerValue)
						{
							return true;
						}
					}
				}
			}
			catch (Exception)
			{
				return false;
			}
			return false;
		}

		private static XDataManager Instance()
		{
			if (OutWallFirstSizeDimXDataUtil.m_xdataMgr == null)
			{
				SchemaManager schemaManager = new SchemaManager(new SchemaData(OutWallFirstSizeDimXDataUtil.m_Guid, OutWallFirstSizeDimXDataUtil.m_schemaName, ""));
                schemaManager.AddField<string>(OutWallFirstSizeDimXDataUtil.m_strFieldName, (UnitType)(-2));
				OutWallFirstSizeDimXDataUtil.m_xdataMgr = new XDataManager(schemaManager);
				OutWallFirstSizeDimXDataUtil.m_xdataMgr.FinishSchema();
			}
			return OutWallFirstSizeDimXDataUtil.m_xdataMgr;
		}

		private static Guid m_Guid = new Guid("075E24FC-97A8-438B-A6DA-DAA3C798E914");

		private static string m_schemaName = "OutWallFirstSizeDimStringId";

		private static string m_strFieldName = "OutWallFirstSizeDimStringField";

		private static XDataManager m_xdataMgr = null;
	}
}
